# -*-coding:utf-8-*-

import paho.mqtt.client as mqtt
from src.log import log
from src.ledController import LedFunc

class Mqtt:
    def __init__(self, broker='192.168.24.132', port=1883, client_id='pi',
                 username='admin', password='OuZhenXian3762',userdata=None):
        self.broker = broker
        self.port = port
        self.client_id = client_id
        self.username = username
        self.password = password
        self.client: mqtt.Client = None
        self.userdata = userdata
        self.log = log

        # 初始化mqtt
        self.get_mqtt(self.userdata)

    # 连接mqtt
    def on_connect(self, client: mqtt.Client, userdata, flags, rc):
        if rc == 0:
            self.log.info(f"mqtt连接成功")
        else:
            self.log.error(f"mqtt连接失败: {rc}")

    #    断开mqtt
    def on_disconnect(self, client: mqtt.Client, userdata, rc):
        if rc != 0:
            self.log.error(f"mqtt断开连接: {rc}")

    # 订阅主题
    def on_subscribe(self,client, userdata, mid, granted_qos):
        self.log.info(f"已订阅主题，消息 ID: {mid}")
    
    # 发布消息
    def on_publish(self, client, userdata, mid):
        self.log.info(f"已发布主题，消息 ID: {mid}")

    # 获取mqtt
    def get_mqtt(self, userdata=None):
        self.client = mqtt.Client(callback_api_version=mqtt.CallbackAPIVersion.VERSION1,
                                  client_id=self.client_id, userdata=userdata)
        self.client.username_pw_set(self.username, self.password)
        self.client.on_connect = self.on_connect
        self.client.on_disconnect = self.on_disconnect
        self.client.on_subscribe = self.on_subscribe
        self.client.on_publish = self.on_publish
        self.client.on_message = LedFunc
        try:
            self.client.connect(self.broker, self.port, keepalive=60)
        except Exception as e:
            self.log.error(f"mqtt连接失败: {e}")

    # 发布消息
    def publish(self, topic, payload, qos=0, retain=False):
        result = self.client.publish(topic, payload, qos, retain)
        if result.rc == mqtt.MQTT_ERR_SUCCESS:
            self.log.info(f"消息已发布到主题 {topic}，消息 ID: {result.mid}")
        else:
            self.log.error(f"消息发布失败，错误码: {result.rc}")

    # 订阅主题
    def subscribe(self, topic, qos=0):
        result, mid = self.client.subscribe(topic, qos)
        if result == mqtt.MQTT_ERR_SUCCESS:
            self.log.info(f"已订阅主题 {topic}，消息 ID: {mid}")
        else:
            self.log.error(f"订阅失败，错误码: {result}")

    def loop_start(self):
        self.client.loop_start()

    def loop_stop(self):
        self.client.loop_stop()


